import { defineStore } from 'pinia'

import { getVtkReaderOrKeyValue } from "../../utils/vtk/vtkReaderList.js";
import { ColorMode, ScalarMode } from "@kitware/vtk.js/Rendering/Core/Mapper/Constants";
import registerStore from '../../stores/index.js'
import { downLoadImage } from "../../utils/transImage.js";
import { hexToRGB } from "../../utils/transformColor.js";
import { vec3 } from 'gl-matrix';
import {
  updateViewOrientationFromBasisAndAxis,
} from '../../utils/utils.js';
export const toolModule = defineStore('TOOL', {
  state () {
    return {
      vtkReaderObj: getVtkReaderOrKeyValue(),
      screenRender: null,
      renderer: null,
      renderWindow: null,
      MODE_TO_AXES: {
        default: {
          forwardAxis: 1,
          forwardOrientation: 1,
          upwardAxis: 2,
          upwardOrientation: 1,
        },
        x: {
          forwardAxis: 0,
          forwardOrientation: 1,
          upwardAxis: 2,
          upwardOrientation: 1,
        },
        y: {
          forwardAxis: 1,
          forwardOrientation: 1,
          upwardAxis: 2,
          upwardOrientation: 1,
        },
        z: {
          forwardAxis: 2,
          forwardOrientation: 1,
          upwardAxis: 1,
          upwardOrientation: -1,
        },
      }
    }
  },
  actions: {
    // 修改全局背景色
    changeBackground (color) {
      registerStore().viewsModulesPinia.view.setBackground(color)
      registerStore().viewsModulesPinia.renderWindow.render()
    },
    // 渲染器截图 模型可视化区域窗口多大 截图就多大
    screenshot () {
      const canvasList = registerStore().viewsModulesPinia.renderWindow.captureImages('image/png', {})
      canvasList.forEach((canvas) => {
        canvas.then((base64) => {
          base64 && downLoadImage(new Date().toString(), base64)
        })
      })
    },
    // 模型向左旋转90度
    rollLeft () {
      const ROTATION_STEP = 2;
      const view = registerStore().viewsModulesPinia.view
      if (view) {
        view.setAnimation(true, this);
        let count = 0;
        let intervalId = null;
        const rotate = () => {
          if (count < 90) {
            count += ROTATION_STEP;
            view.rotate(+ROTATION_STEP);
          } else {
            clearInterval(intervalId);
            view.setAnimation(false, this);
          }
        };
        intervalId = setInterval(rotate, 1);
      }
    },
    // 模型向右旋转90度
    rollRight () {
      const ROTATION_STEP = 2;
      const view = registerStore().viewsModulesPinia.view
      if (view) {
        view.setAnimation(true, this);
        let count = 0;
        let intervalId = null;
        const rotate = () => {
          if (count < 90) {
            count += ROTATION_STEP;
            view.rotate(-ROTATION_STEP);
          } else {
            clearInterval(intervalId);
            view.setAnimation(false, this);
          }
        };
        intervalId = setInterval(rotate, 1);
      }
    },
    // 重置
    recoveryPerspective () {
      this.renovate()
    },
    // 视角切换至x,y,z轴
    recoveryPerspectiveXYZ (mode) {
      updateViewOrientationFromBasisAndAxis(
        registerStore().viewsModulesPinia.view,
        registerStore().viewsModulesPinia.viewOrientation,
        mode,
        100
      )
    },
    // 刷新视图
    renovate () {
      registerStore().viewsModulesPinia.renderer.resetCamera()
      // registerStore().viewsModulesPinia.renderer.getActiveCamera().zoom(1.5);
      registerStore().viewsModulesPinia.renderWindow.render();
    },
    // 显示隐藏模型
    showHidden (value, index) {
      registerStore().viewsModulesPinia.showHiddenModel(value, index)
      const modelActorArr = registerStore().viewsModulesPinia.modelActorArr
      modelActorArr[index].actor.setVisibility(value)
      registerStore().viewsModulesPinia.renderWindow.render();
    },
    // 删除模型
    removeActor (index) {
      const modelActorArr = registerStore().viewsModulesPinia.modelActorArr
      const actor = modelActorArr[index].actor
      const mapper = modelActorArr[index].mapper
      registerStore().viewsModulesPinia.view.getRenderer().removeActor(actor);
      mapper.delete();
      actor.delete();
      registerStore().viewsModulesPinia.renderWindow.render()
    },
    // 切换模型颜色
    changeModelColor (value, index) {
      const modelActorArr = registerStore().viewsModulesPinia.modelActorArr
      if (!value) {
        modelActorArr[index].mapper.set({
          colorByArrayName: '',
          colorMode: 1,
          interpolateScalarsBeforeMapping: false,
          scalarMode: 1,
          scalarVisibility: false
        })
        registerStore().viewsModulesPinia.renderWindow.render()
        return
      }
      const [location, colorByArrayName] = value.split(':');
      const interpolateScalarsBeforeMapping = location === 'PointData';
      let colorMode = ColorMode.DEFAULT;
      let scalarMode = ScalarMode.DEFAULT;
      const scalarVisibility = location.length > 0;
      const lutProxy = registerStore().viewsModulesPinia.proxyManager.getLookupTable(colorByArrayName);
      console.log('lutProxy', lutProxy.getDataRange());
      if (scalarVisibility) {
        const newArray = modelActorArr[index].source[`get${location}`]().getArrayByName(colorByArrayName);
        registerStore().viewsModulesPinia.activeArray = newArray;
        colorMode = ColorMode.MAP_SCALARS;
        scalarMode =
          location === 'PointData'
            ? ScalarMode.USE_POINT_FIELD_DATA
            : ScalarMode.USE_CELL_FIELD_DATA;

        const numberOfComponents = registerStore().viewsModulesPinia.activeArray.getNumberOfComponents();
        if (numberOfComponents > 1) {
          if (modelActorArr[index].mapper.getLookupTable()) {
            const lut = modelActorArr[index].mapper.getLookupTable(colorByArrayName);
            lut.setVectorModeToMagnitude();
          }
        }
        // registerStore().viewsModulesPinia.scalarBarActor.setAxisLabel(colorByArrayName);
      }
      modelActorArr[index].mapper.set({
        colorByArrayName,
        colorMode,
        interpolateScalarsBeforeMapping,
        scalarMode,
        scalarVisibility
      })
      registerStore().viewsModulesPinia.renderWindow.render()
    },
    setDiffuseReflection (rgb,index) {
      const color = hexToRGB(rgb);
      const modelActorArr = registerStore().viewsModulesPinia.modelActorArr
      modelActorArr[index].actor.getProperty().setDiffuseColor(color.r / 255.0, color.g / 255.0, color.b / 255.0);
      modelActorArr[index].actor.getProperty().setAmbientColor(color.r / 255.0, color.g / 255.0, color.b / 255.0);
      registerStore().viewsModulesPinia.renderWindow.render()
    },
    representationChange (value,index) {
      const modelActorArr = registerStore().viewsModulesPinia.modelActorArr 
      const [visibility, representation, edgeVisibility] = value.split(':').map(Number);
      modelActorArr[index].actor.getProperty().set({ representation, edgeVisibility });
      modelActorArr[index].actor.setVisibility(!!visibility);
      registerStore().viewsModulesPinia.renderWindow.render();
    }
  }
})